package cn.mrcode.mrweb.controller;

import cn.mrcode.mrweb.model.Customer;
import cn.mrcode.mrweb.service.CustomerService;
import cn.mrcode.smartFramework.annotation.Action;
import cn.mrcode.smartFramework.annotation.Controller;
import cn.mrcode.smartFramework.annotation.Inject;
import cn.mrcode.smartFramework.bean.Data;
import cn.mrcode.smartFramework.bean.FileParam;
import cn.mrcode.smartFramework.bean.Param;
import cn.mrcode.smartFramework.bean.View;
import cn.mrcode.smartFramework.helper.ServletHelper;
import cn.mrcode.smartFramework.helper.UploadHelper;

import java.util.List;
import java.util.Map;

/**
 * Created by zhuqiang on 2015/10/17 0017.
 */
@Controller
public class CustomerController {
    @Inject
    private CustomerService customerService;

    @Action(value = "/customer",method = "GET")
    public View list(){
        List<Customer> customerList = customerService.getCustomerList();
        return new View("customer.jsp").addModel("customerList",customerList);
    }

    @Action(value = "/customer_edit",method = "GET")
    public View edit(Param param){
        long id = param.getLong("id");
        String idRequest = ServletHelper.getRquest().getParameter("id");
        System.out.println("测试框架提供的servletApi是否好用：" + idRequest);
        Customer customer = customerService.getCustomer(id);
        return new View("customer.jsp").addModel("customer",customer);
    }
    @Action(value = "/customer_update",method = "POST")
    public Data update(Param param){
        long id = param.getLong("id");
        Customer customer = customerService.getCustomer(id);
        customerService.updateCustomer(id,param.getFieldMap());
        return new Data("修改成功");
    }

    @Action(value = "/customer_create_pre",method = "GET")
    public View create_pre(){
        return new View("customer_create.jsp");
    }

    @Action(value = "/customer_create",method = "POST")
    public Data create(Param param){
        FileParam file = param.getFile("photo");
        String basePath = "d:/asset/image/";
        UploadHelper.uploadFile(basePath,file);

        Map<String, Object> fieldMap = param.getFieldMap();
        fieldMap.remove("id");
        fieldMap.put("photo","/asset/image/" + file.getFileName());
        boolean customer = customerService.createCustomer(fieldMap);
        return new Data(true);
    }

    @Action(value = "/customer_delete",method = "delete")
    public Data delete(Param param){
        long id = param.getLong("id");
        boolean b = customerService.deleteCustomer(id);
        return new Data(b);
    }
}
